package com.kingdee.openimport.patch_service.service.impl;

import com.kingdee.openimport.patch_service.service.IPatchRedisService;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.Set;

/**
 * Created by Niki on 2018/4/21 14:39
 */
@Service
public class PatchRedisServiceImpl implements IPatchRedisService {
    @Resource
    JedisSentinelPool pool;

    private static final String PATCH_FILE_KEY_PREFIX = "EAS:PATCH:FILE:";
    private static final String PATCH_VERSION_KEY_PREFIX = "EAS:PATCH:VERSION:";

    private String toRedisKey(String prefix, String key) {
        return prefix + key;
    }

    @Override
    public byte[] getPatchByte(String key) {
        Jedis jedis = pool.getResource();
        try {
            key = toRedisKey(PATCH_FILE_KEY_PREFIX, key);
            return jedis.get(key.getBytes(Charset.forName("UTF-8")));
        } finally {
            jedis.close();
        }
    }

    @Override
    public Set<String> getAllPatchKeyByVersion(String version) {
        Jedis jedis = pool.getResource();
        try {
            version = toRedisKey(PATCH_VERSION_KEY_PREFIX, version);
            return jedis.sinter(version);
        } finally {
            jedis.close();
        }
    }

    @Override
    public void putPatch(String key, byte[] patch) {
        Jedis jedis = pool.getResource();
        try {
            key = toRedisKey(PATCH_FILE_KEY_PREFIX, key);
            jedis.set(key.getBytes(Charset.forName("UTF-8")), patch);
        } finally {
            jedis.close();
        }
    }

    @Override
    public long setPatchKey(String version, String patchKey) {
        Jedis jedis = pool.getResource();
        try {
            version = toRedisKey(PATCH_VERSION_KEY_PREFIX, version);
            patchKey = toRedisKey(PATCH_FILE_KEY_PREFIX, patchKey);
            return jedis.sadd(version, patchKey);
        } finally {
            jedis.close();
        }
    }

    @Override
    public long setPatchKeys(String version, String... patchKeys) {
        Jedis jedis = pool.getResource();
        try {
            version = toRedisKey(PATCH_VERSION_KEY_PREFIX, version);
            int len = patchKeys.length;
            String[] patchKeys_ = new String[len];
            for (int i = 0; i < len; i++) {
                patchKeys_[i] = toRedisKey(PATCH_FILE_KEY_PREFIX, patchKeys[i]);
            }
            return jedis.sadd(version, patchKeys_);
        } finally {
            jedis.close();
        }
    }
}
